package com.xinxin.blockchain.util.legacy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.xinxin.base.util.CommonUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

/**
 * Created by Chris_He on 2018/10/26.
 */
public class UploadUtil {

    private static final Logger log = LoggerFactory.getLogger(UploadUtil.class);

    private static final String END_POINT = "http://oss-cn-hongkong.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI05eRy2HaqTg2";
    private static final String ACCESS_KEY_SECRET = "IyDoGeOmlJWJcRZZeuGfnyIJ8ZjO75";
    private static final String BUCKET_NAME = "bzzhibo";
    private static final String PIC_PREFIX = "https://fileup.ickapay.com";

    public static JSONArray uploadPic(MultipartFile[] pics, Integer width, Integer height) {
        JSONArray jsonArray = new JSONArray();
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 上传文件流。
        for (MultipartFile pic : pics) {
            if (null != width && null != height) {
                try {
                    //将上传的图片设置
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    Thumbnails.of(pic.getInputStream()).size(width, height).toOutputStream(outputStream);//变为150*150,遵循原图比例缩或放到400*某个高度
                } catch (IOException e) {
                    log.error(Thread.currentThread() + "——上传图片失败：", e);
                }
            }

            String originalFilename = pic.getOriginalFilename();//获取文件名
            String fileName = subFileName(originalFilename);//获取真实的文件名
            String randonFileName = generateRandonFileName(fileName);//生成随机的文件名
            String randomDir = generateRandomDir(randonFileName);//生成一个二级目录

            String key = "file" + randomDir + "/" + randonFileName;
            String picUrl = PIC_PREFIX + key;
            try {
                ossClient.putObject(BUCKET_NAME, key, pic.getInputStream());
            } catch (IOException e) {
                log.error(Thread.currentThread() + "——上传图片失败：", e);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("picUrl", picUrl);
            jsonArray.add(jsonObject);
        }
        // 关闭OSSClient。
        ossClient.shutdown();
        return jsonArray;
    }

    /**
     * 得到真实文件名
     *
     * @param fileName
     * @return
     */
    public static String subFileName(String fileName) {
        //查找最后一个 \ (文件分隔符)位置
        int index = fileName.lastIndexOf(File.separator);
        if (index == -1) {
            //没有分隔符，说明是真实名称
            return fileName;
        } else {
            return fileName.substring(index + 1);
        }
    }

    /**
     * 获得随机UUID文件名
     *
     * @param fileName
     * @return
     */
    public static String generateRandonFileName(String fileName) {
        //首相获得扩展名，然后生成一个UUID码作为名称，然后加上扩展名
        String ext = getFileExtension(fileName);
        return CommonUtil.generateUUID() + "." + ext;
    }

    /**
     * 获取文件扩展名
     *
     * @param fileName
     * @return
     */
    public static String getFileExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    /**
     * 获得hashcode 生成二级目录
     *
     * @param uuidFileName
     * @return
     */
    public static String generateRandomDir(String uuidFileName) {
        int hashCode = uuidFileName.hashCode();//得到它的hashcode编码
        //一级目录
        int d1 = hashCode & 0xf;
        //二级目录
        int d2 = (hashCode >> 4) & 0xf;
        return "/imgOneVideo" + d1 + "/" + d2;
    }

    public static void main(String[] args) {
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
//        String originalFilename = pic.getOriginalFilename();//获取文件名
//        String fileName = UploadUtils.subFileName(originalFilename);//获取真实的文件名
//        String randonFileName = UploadUtils.generateRandonFileName(fileName);//生成随机的文件名
//        String randomDir = UploadUtils.generateRandomDir(randonFileName);//生成一个二级目录

//        String big = "file" + randomDir + "/" + randonFileName;
//        String bigpic = PIC_PREFIX + big;
        ossClient.deleteObject(BUCKET_NAME, "file/qrCode/D201807191548032761864.png");
    }
}
